<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">

<head>
    {% load static %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">

	<link rel="stylesheet" href="{% static 'css/ie8.css' %}">
	<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" href="{% static 'css/ImgCropping.css' %}">
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
    <script src="{% static 'js/cropper.min.js' %}"></script><!-- jQuery is required -->


	<script src="{% static 'js/jquery.dropotron.min.js' %}"></script>
	<script src="{% static 'js/skel.min.js' %}"></script>

	<script src="{% static 'js/init.js' %}"></script>

	<noscript>
			<link rel="stylesheet" href="{% static 'css/skel-noscript.css' %}" />
			<link rel="stylesheet" href="{% static 'css/style-desktop.css' %}" />
			<link rel="stylesheet" href="{% static 'css/style-noscript.css' %}" />
	</noscript>

    <link  href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css" rel="stylesheet">
    <title></title>
</head>

<body class="homepage">

		<!-- Header -->
			<div id="header">

				<!-- Inner -->
					<div class="inner">
						<header>
							<h1><a href="#" id="logo">Graphic Process</a></h1>
							<hr />
							<span class="byline">Image processing website</span>
						</header>
						<footer>
							<a href="#banner" class="button circled scrolly">Start</a>
						</footer>
					</div>

				<!-- Nav -->
					<nav id="nav">
						<ul>
                           <li><a href="{% url 'introduction' %}">Introduction</a></li>
							<li><a href="{% url 'index' %}">Home/Basics</a></li>
							<li><a href="{% url 'ocr' %}">Recognition</a></li>
						</ul>
					</nav>

			</div>

		<!-- Banner -->
		<div id="banner">
			<div style=" display: flex;justify-content: center;align-items: center;">
				<table border="0">
            <tr>
				<td width="550">
					<div class="upload-wrap anticon" nv-file-drop="" uploader="uploader">
						<input class="file-ele" type="file" file-model="image" name="image" id="imgin" nv-file-select
							   uploader="uploader" multiple accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff"/>
						<div class="file-open"><em class="icon icon-upload"></em>Uploade</div>
					</div>
					<div>
						<input type="button" class="buttondow" id="crop" value="Tailor"/>
						<input type="button" class="buttondow" id="reset" value="Reset" onclick="todo('reset')"/>
					</div>
					<div style="height:5px"></div>
					<div class="container1">
						<img src="https://tse4-mm.cn.bing.net/th/id/OIP-C.IYnZUDBuyOLvkPOnkkfpLwHaHa?pid=ImgDet&rs=1" id="img" class="cimage" >
					</div>
					<div style="height:5px"></div>
					<div>
						<input type="button" class="buttondow" id="savebtn" value="Download" onclick="save()"/>
					</div>
				</td>

                <td width="250">
                    <div>
						&nbsp&nbsp&nbsp&nbspBrightness Change</br>
                        <div style="height:10px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="range" id="btn8" min="-100" max="100" onchange="todo0('brightness')" value="0"></br>
                        &nbsp&nbsp&nbsp&nbspContrast Change</br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="range" id="btn9" min="-100" max="100" onchange="todo0('contrast')"></br>
                        <div style="height:17px"></div>
                        &nbsp&nbsp&nbsp&nbspSmooth</br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn18" value="Mean Filter" onclick="todo0('mean')"></br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn19" value="Gaussian Filter" onclick="todo0('gaussian')"></br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn20" value="Median Filter" onclick="todo0('median')"></br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn21" value="Two-sided Filter" onclick="todo0('two-sided')"></br>
                    </div>
                </td>
                <td width="250">
                    <div>
						&nbsp&nbsp&nbsp&nbspEdge Detection</br>
                        <div style="height:10px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn1" value="Roberts" onclick="todo('Roberts')"></br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn2" value="Sobel" onclick="todo('Sobel')"></br>
						<div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn2_1" value="Prewitt" onclick="todo('Prewitt')"></br>
						<div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn3" value="Laplacian" onclick="todo('Laplacian')"></br>
						<div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn5" value="Canny" onclick="todo('Canny')"></br>
						<div style="height:10px"></div>&nbsp&nbsp&nbsp&nbspMirroring</br>
                        <div style="height:10px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn6" value="Horizon" onclick="todo('horizonFilp')"></br>
                        <div style="height:17px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn7" value="Vertical" onclick="todo('verticalFilp')"></br>
                    </div>
                </td>
                <td width="250">
                    <div>
                        &nbsp&nbsp&nbsp&nbspMorphological Processing</br>
                        <div style="height:15px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn10" value="Swell" onclick="todo('swell')"></br>
                        <div style="height:18px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn11" value="Corrosion" onclick="todo('etch')"></br>
                        <div style="height:18px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn12" value="Open" onclick="todo('open_compute')"></br>
                        <div style="height:18px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn13" value="Close" onclick="todo('close_compute')"></br>
                        <div style="height:18px"></div>&nbsp&nbsp&nbsp&nbspNoise</br>
                        <div style="height:15px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn15" value="SpicedSalt" onclick="todo('pepperAndSalt')"></br>
                        <div style="height:18px"></div>&nbsp&nbsp&nbsp&nbsp
                        <input type="button" class="button" id="btn16" value="Gaussian" onclick="todo('gas_noise')"></br>
                    </div>
                </td>
            </tr>
        </table>
			</div>


		</div>
	<!--图片裁剪框 start-->
<div style="display: none" class="tailoring-container">
    <div class="black-cloth" onclick="closeTailor(this)"></div>
    <div class="tailoring-content">
            <div class="tailoring-content-one">
                <label title="图片裁剪" class="l-btn choose-btn">
                    <p>图片裁剪</p>
                </label>
                <div class="close-tailoring"  onclick="closeTailor(this)">×</div>
            </div>
            <div class="tailoring-content-two">
                <div class="tailoring-box-parcel">
                    <img id="tailoringImg">
                </div>
                <div class="preview-box-parcel">
                    <p>图片预览：</p>
                    <div class="square previewImg"></div>
                </div>
            </div>
            <div class="tailoring-content-three">
                <button class="l-btn cropper-reset-btn">复位</button>
                <button class="l-btn cropper-rotate-btn">旋转</button>
                <button class="l-btn cropper-scaleX-btn">换向</button>
                <button class="l-btn sureCut" id="sureCut">确定</button>
            </div>
        </div>
</div>
	</body>

<script>
var fileInput = document.querySelector('input[type=file]');
var previewImg = document.querySelector('img');

var fileInput = document.querySelector('input[type=file]');
var previewImg = document.querySelector('img');

fileInput.addEventListener('change', function () {
    var file = this.files[0];
    var reader = new FileReader();
    // 调用reader.readAsDataURL()方法，把图片转成base64
    reader.readAsDataURL(file);
    // 监听reader对象的的onload事件，当图片加载完成时，把base64编码賦值给预览图片
    reader.addEventListener("load", function () {
       previewImg.src = reader.result;
       // 直接将照片暂存
        var img = $('#imgin')[0].files[0];
        var formData = new FormData;
        formData.append("image", img);
        $.ajax({
            url: 'photoIn', //请求路径
            type: 'POST', // 请求类型
            data: formData, // 请求数据
            headers: {"X-CSRFToken": $.cookie('csrftoken')},
            dataType: "text", // 返回数据格式
            contentType: false, //表示不处理数据
            processData: false,
            async: false,
            cache: false,
            success: function (data) {
                if (data != null){
                    console.log("返回的数据："+data)
                    //$('#image-after').append("<img width='500' id='after' src="+'"data:image/jpg;base64,'+data+'">')
                    //previewImg.src="data:image/jpg;base64,"+data
                    //console.log("OK");
                }
                if (data == null){
                    console.log("返回为空")
                }
            },
            error: function (data) {
                console.log("返回失败")
                console.log(data);
            }
        });
        }, false);
    // 调用reader.readAsDataURL()方法，把图片转成base64
    //reader.readAsDataURL(file);
 }, false);

const container1 = document.querySelector('.container1');
// 全局变量
let result,
    x,
    y,
    scale = 1,
    minScale = 0.5,
    maxScale = 4,
    isPointerdown = false, // 按下标识
    point = { x: 0, y: 0 }, // 第一个点坐标
    diff = { x: 0, y: 0 }, // 相对于上一次pointermove移动差值
    lastPointermove = { x: 0, y: 0 }; // 用于计算diff
// 图片加载完成后再绑定事件
previewImg.addEventListener('load', function () {
    result = getImgSize(previewImg.naturalWidth, previewImg.naturalHeight, container1.clientWidth, container1.clientHeight);
    previewImg.style.width = result.width + 'px';
    previewImg.style.height = result.height + 'px';
    x = (container1.clientWidth - result.width) * 0.5;
    y = (container1.clientHeight - result.height) * 0.5;
    previewImg.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(1)';
    // 拖拽查看
    drag();
    // 滚轮缩放
    wheelZoom();
});
/**
* 获取图片缩放尺寸
* @param {number} naturalWidth
* @param {number} naturalHeight
* @param {number} maxWidth
* @param {number} maxHeight
* @returns
*/
function getImgSize(naturalWidth, naturalHeight, maxWidth, maxHeight) {
    const imgRatio = naturalWidth / naturalHeight;
    const maxRatio = maxWidth / maxHeight;
    let width, height;
    // 如果图片实际宽高比例 >= 显示宽高比例
    if (imgRatio >= maxRatio) {
        if (naturalWidth > maxWidth) {
            width = maxWidth;
            height = maxWidth / naturalWidth * naturalHeight;
        } else {
            width = naturalWidth;
            height = naturalHeight;
        }
    } else {
        if (naturalHeight > maxHeight) {
            width = maxHeight / naturalHeight * naturalWidth;
            height = maxHeight;
        } else {
            width = naturalWidth;
            height = naturalHeight;
        }
    }
    return { width: width, height: height }
}
// 拖拽查看
function drag() {
    // 绑定 pointerdown
    previewImg.addEventListener('pointerdown', function (e) {
        isPointerdown = true;
        previewImg.setPointerCapture(e.pointerId);
        point = { x: e.clientX, y: e.clientY };
        lastPointermove = { x: e.clientX, y: e.clientY };
    });
    // 绑定 pointermove
    previewImg.addEventListener('pointermove', function (e) {
        if (isPointerdown) {
            const current1 = { x: e.clientX, y: e.clientY };
            diff.x = current1.x - lastPointermove.x;
            diff.y = current1.y - lastPointermove.y;
            lastPointermove = { x: current1.x, y: current1.y };
            x += diff.x;
            y += diff.y;
            previewImg.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(' + scale + ')';
        }
        e.preventDefault();
    });
    // 绑定 pointerup
    previewImg.addEventListener('pointerup', function (e) {
        if (isPointerdown) {
            isPointerdown = false;
        }
    });
    // 绑定 pointercancel
    previewImg.addEventListener('pointercancel', function (e) {
        if (isPointerdown) {
            isPointerdown = false;
        }
    });
}
// 滚轮缩放
function wheelZoom() {
    container1.addEventListener('wheel', function (e) {
       let ratio = 1.1;
        // 缩小
        if (e.deltaY > 0) {
            ratio = 1 / 1.1;
        }
        // 限制缩放倍数
        const _scale = scale * ratio;
        if (_scale > maxScale) {
            ratio = maxScale / scale;
            scale = maxScale;
        } else if (_scale < minScale) {
            ratio = minScale / scale;
            scale = minScale;
        } else {
            scale = _scale;
        }
        // 目标元素是img说明鼠标在img上，以鼠标位置为缩放中心，否则默认以图片中心点为缩放中心
        if (e.target.tagName === 'IMG') {
            const origin = {
                x: (ratio - 1) * result.width * 0.5,
                y: (ratio - 1) * result.height * 0.5
            };
            // 计算偏移量
            x -= (ratio - 1) * (e.clientX - x) - origin.x;
            y -= (ratio - 1) * (e.clientY - y) - origin.y;
        }
        previewImg.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(' + scale + ')';
        e.preventDefault();
    });
}

//弹出框水平垂直居中
(window.onresize = function () {
    var win_height = $(window).height();
    var win_width = $(window).width();
    if (win_width <= 768){
        $(".tailoring-content").css({
            "top": (win_height - $(".tailoring-content").outerHeight())/2,
            "left": 0
        });
    }else{
        $(".tailoring-content").css({
            "top": (win_height - $(".tailoring-content").outerHeight())/2,
            "left": (win_width - $(".tailoring-content").outerWidth())/2
        });
    }
})();

    //弹出图片裁剪框
    $("#crop").on("click",function () {
        $(".tailoring-container").toggle();
        getImg();
    });
    //获得图像
    function getImg(file) {
        if(previewImg.src=="" || previewImg.src=="https://tse4-mm.cn.bing.net/th/id/OIP-C.IYnZUDBuyOLvkPOnkkfpLwHaHa?pid=ImgDet&rs=1") {
            alert("还未选择图片");
            closeTailor();
        }else{
            $('#tailoringImg').cropper('replace',previewImg.src,false);//默认false，适应高度，不失真
        }
    }
    //cropper图片裁剪
    $('#tailoringImg').cropper({
        aspectRatio: 1/1,//默认比例
        preview: '.previewImg',//预览视图
        guides: false,  //裁剪框的虚线(九宫格)
        autoCropArea: 0.5,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
        movable: false, //是否允许移动图片
        dragCrop: true,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
        movable: true,  //是否允许移动剪裁框
        resizable: true,  //是否允许改变裁剪框的大小
        zoomable: false,  //是否允许缩放图片大小
        mouseWheelZoom: false,  //是否允许通过鼠标滚轮来缩放图片
        touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
        rotatable: true,  //是否允许旋转图片
        crop: function(e) {
            // 输出结果数据裁剪图像。
        }
    });
    //旋转
    $(".cropper-rotate-btn").on("click",function () {
        $('#tailoringImg').cropper("rotate", 45);
    });
    //复位
    $(".cropper-reset-btn").on("click",function () {
        $('#tailoringImg').cropper("reset");
    });
    //换向
    var flagX = true;
    $(".cropper-scaleX-btn").on("click",function () {
        if(flagX){
            $('#tailoringImg').cropper("scaleX", -1);
            flagX = false;
        }else{
            $('#tailoringImg').cropper("scaleX", 1);
            flagX = true;
        }
        flagX != flagX;
    });

    //裁剪后的处理
    $("#sureCut").on("click",function () {
        if ($("#tailoringImg").attr("src") == null ){
            return false;
        }else{
            var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
            var base64url = cas.toDataURL('image/jpg'); //转换为base64地址形式
            $("#img").prop("src",base64url);//显示为图片的形式
            // 直接将照片暂存
            $.ajax({
                url: 'photoIn2', //请求路径
                type: 'POST', // 请求类型
                data: { 'base64url':base64url }, // 请求数据
                headers: {"X-CSRFToken": $.cookie('csrftoken')},
                dataType: "text", // 返回数据格式
                async: false,
                cache: false,
                success: function (data) {
                    if (data != null){
                        console.log("OK");
                    }
                    if (data == null){
                        console.log("返回为空")
                    }
                },
                error: function (data) {
                    console.log("返回失败")
                    console.log(data);
                }
            });
            //关闭裁剪框
            closeTailor();
        }
    });
    //关闭裁剪框
    function closeTailor() {
        $(".tailoring-container").toggle();
    }




 //下载处理后图片
 function save() {
        if (!previewImg) {
            alert("没有图片！")
            return false;
        }
        var url = previewImg.src; // 获取图片地址
        var a = document.createElement('a'); // 创建一个a节点插入的document
        var event = new MouseEvent('click') // 模拟鼠标click点击事件
        a.download = '处理后图片.png' // 设置a节点的download属性值
        a.href = url; // 将图片的src赋值给a节点的href
        a.dispatchEvent(event)
    }

//图像操作1，具体操作看参数operation
 function todo0(operation) {
    if(!operation || operation == ''){
        alert('空操作');
        return false;
    }
    else if(operation=='brightness'){
        // range类的input标签
        value = document.getElementById('btn8').value;
        url = 'todo0'+'/?todo=brightness'+'&value='+value;
    }
    else if(operation=='contrast'){
        // range类的input标签
        value = document.getElementById('btn9').value;
        url = 'todo0'+'/?todo=contrast'+'&value='+value;
    }
    else{
        url = 'todo0'+'/?todo='+operation;
    }

     $.ajax({
        url: url, //请求路径
        type: 'GET', // 请求类型
        data: '', // 请求数据
        dataType: "text", // 返回数据格式
        async: false,
        cache: false,
        success: function (data) {
            if (data != null){
                //console.log("返回的数据："+data)
                //$('#image-after').append("<img width='500' id='after' src="+'"data:image/jpg;base64,'+data+'">')
                if(data == "no") alert('未选择图片！');
                else if(data == "OK") ;
                else previewImg.src="data:image/jpg;base64,"+data
            }
            if (data == null){
                console.log("返回数据为空")
            }
        },
        error: function (data) {
            console.log("数据返回失败")
            console.log(data);
        }
    });

 }

 //图像操作2，具体操作看参数operation
 function todo(operation) {
    if(!operation || operation == ''){
        alert('空操作');
        return false;
    }
     url = 'todo'+'/?todo='+operation;
     $.ajax({
        url: url, //请求路径
        type: 'GET', // 请求类型
        data: '', // 请求数据
        dataType: "text", // 返回数据格式
        async: false,
        cache: false,
        success: function (data) {
            if (data != null){
                //console.log("返回的数据："+data)
                //$('#image-after').append("<img width='500' id='after' src="+'"data:image/jpg;base64,'+data+'">')
                if(data == "no") alert('未选择图片！');
                else previewImg.src="data:image/jpg;base64,"+data
            }
            if (data == null){
                console.log("返回数据为空")
            }
        },
        error: function (data) {
            console.log("数据返回失败")
            console.log(data);
        }
    });

 }
</script>

</html>